<script setup lang="ts">
import { getMenuList } from "@/api/system/menu/menu";
import {
  addRole,
  deleteRole,
  getRole,
  getRoleList,
  getRoleMenuList,
  upRole,
} from "@/api/system/role/role.ts";
import { ElMessage, type FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import message from "@/utils/message";
import { handleTree } from "@/utils/ruoyi";
interface role {
  roleId: number | null;
  roleName: string;
  description: string;
  status: number;
  createTime: string;
  updateTime: string;
}
const roleList = ref<role[]>([]);
const loading =ref(false)
const form = ref({
  roleId: null,
  roleName: "",
  description: "",
  status: 1,
  createTime: "",
  updateTime: "",
  permsList: [],
});
const formRef = ref();
const menuRef = ref();
const props = {
  label: "name",
  value: "id",
};

//菜单权限数据
const menuList = ref();
// 查询角色列表
async function getRoleData() {
  loading.value=true
  await getRoleList().then((response) => {
    roleList.value = response.data.rows;
  });
  loading.value=false
}
//查询所有权限
function getMenu() {
  getMenuList().then((response) => {
    menuList.value = handleTree(response.data.data, "id", "parentId", "children")
  });
}
// 表单校验
const roleNameValidator = (rule: any, value: any, callback: any) => {
  if (!value.trim()) {
    callback(new Error("不能为空"));
  } else if (value.trim().length < 1 || value.trim().length > 20) {
    callback(new Error("长度为1到20位"));
  } else {
    callback();
  }
};
const rules = reactive({
  roleName: [
    {
      required: true,
      validator: roleNameValidator,
      trigger: "blur",
    },
  ],
});
const dialogVisible = ref(false);
const title = ref("");

//新增按钮
const AddForm = () => {
  //获取所有菜单
  getMenu();
  isSumbit.value = true;
  dialogVisible.value = true;
  title.value = "新增角色";
};
//修改按钮
const handleEdit = (row: any) => {
  isSumbit.value = false;
  dialogVisible.value = true;
  title.value = "修改角色";
  //获取所有菜单
  getMenu();
  getRole(row.roleId).then((response) => {
    form.value = response.data.data;
    //获取已有权限菜单并回显
    getRoleMenuList(row.roleId).then((response) => {
      form.value.permsList = response.data.data;
      menuRef.value.setCheckedKeys(form.value.permsList);
    });
  });
};
// 删除角色
const handleDelete = async (row: any) => {
  await deleteRole(row.roleId).then((response) => {
    ElMessage.success(response.data.msg);
  });;
  getRoleData();
};

//提交表单
//提交按钮标识
const isSumbit = ref(false);
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isSumbit.value) {
        form.value.permsList = menuRef.value.getCheckedKeys();
        await addRole(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });;
      } else {
        form.value.permsList = menuRef.value.getCheckedKeys();
        await upRole(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });;
      }
      dialogVisible.value = false;
      getRoleData();
    }
  });
};

//表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
getRoleData();
</script>
<template>
  <el-button type="primary" @click="AddForm">新增</el-button>
  <el-divider />
  <el-table v-loading="loading" :data="roleList" style="width: 100%; height: 70vh">
    <el-table-column prop="roleId" label="id" width="180" />
    <el-table-column prop="roleName" label="角色名称" width="180" />
    <el-table-column prop="description" label="角色描述" />
    <el-table-column prop="status" label="状态" width="180">
      <template #default="scope">
        <el-tag :value="scope.row.status">{{
          scope.row.status ? "启用" : "停用"
        }}</el-tag>
      </template></el-table-column
    >
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column prop="updateTime" label="修改时间" />
    <el-table-column label="操作" width="250">
      <template #default="scope">
        <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">
          修改
        </el-button>
        <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row)">
          <template #reference>
            <el-button link type="primary" icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加或修改角色信息 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    @close="resetForm(formRef)"
    style="min-width: 600px"
  >
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="roleName" label="角色名称">
            <el-input v-model.trim="form.roleName" placeholder="角色名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="description" label="角色描述">
            <el-input v-model="form.description" placeholder="角色描述"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status" label="状态">
            <template #label>
              <span>
                <el-tooltip
                  content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                  placement="top"
                >
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                状态
              </span>
            </template>
            <el-radio-group v-model="form.status">
              <el-radio :value="0">禁用</el-radio>
              <el-radio :value="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="permsList" label="菜单权限">
            <el-tree-select
              v-model="form.permsList"
              :data="menuList"
              ref="menuRef"
              node-key="id"
              multiple
              :render-after-expand="false"
              show-checkbox
              :props="props"
              placeholder="选择菜单"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="" label="">
            <el-button type="primary" @click="submitForm(formRef)"> 确定 </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
